package com.woniuxy.book.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JWTUtil {

    private static String sect = "sdifsjhgsjfksfksjflsjkfhsdkdfhblkadkwhfkiwef";

    //生成token
    //键值对包含用户信息
    //以分钟为单位的时间 代表jwt的有效时间
    public static String createToken(Map<String, Object> body, Integer mil) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.builder()
                .setClaims(body) //内容
                .setExpiration(new Date(System.currentTimeMillis() + mil * 60 * 1000))//过期时间
                .signWith(key)
                .compact();
    }

    //解析token
    public static Claims parseToken(String token) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.parserBuilder().setSigningKey(key)
                .build().parseClaimsJws(token).getBody();
    }

    public static Object getSubject(String token){
        return parseToken(token).get("subject");
    }

}
